const { validationResult } = require('express-validator');
const {
    router,
    Result,
    querySql,
    queryOne,
    VbenResult
} = require('../connect');

const boom = require('boom');
const { CODE_SUCCESS, TYPE_SUCCESS } = require('../utils/constant');

router.post('/', async (req, res) => {

    const err = validationResult(req);
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        // let sql = 'select * from post';

        const page_num = req.body.pageNumber || 1  //当前的num
        const page_size = req.body.pageSize || 20  //当前页的数量
        const m = (parseInt(page_num) - 1) * parseInt(page_size)

        const sql = `select * from post limit ${page_size} offset ${m}`
        const sqlTotal = 'select count(1) from post'

        const result = await querySql(sql)
        const total = await querySql(sqlTotal)

        res.json(new VbenResult({
            code: CODE_SUCCESS,
            message: '查询成功',
            result: {
                data: result,
                total: total[0]['count(1)']
            },
            type: TYPE_SUCCESS,
        }))
        // querySql(sql).then(result => {
        //     console.log(result)
        //     // res.json(new Result({
        //     //     code: CODE_SUCCESS,
        //     //     data: result
        //     // }))
        //     res.json(new VbenResult({
        //         code: CODE_SUCCESS,
        //         message: '查询成功',
        //         result,
        //         type: TYPE_SUCCESS
        //     }))
        // })
    }


})

router.post('/list', (req, res, next) => {
    const err = validationResult(req);
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {

        const page_num = req.body.pageNumber || 0  //当前的num
        const page_size = req.body.pageSize || 20  //当前页的数量
        const m = (parseInt(page_num) - 1) * parseInt(page_size)

        const sql = `select * from user_t limit ${m},${page_size}`
        const sqlTotal = 'select count(*) as total from user_t'
        querySql(sql).then(result => {
            querySql(sqlTotal).then(totalCount => {
                res.json({
                    code: CODE_SUCCESS,
                    msg: '查询成功',
                    data: result,
                    page_num: page_num,
                    page_size: page_size,
                    total: totalCount[0].total
                })
            })
        })
    }


})

module.exports = router;